//
//  ZJSILocationView.m
//  ShangHaiHuDongApp
//
//  Created by ZJ on 2017/6/13.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJSILocationView.h"
#import "ZJLocation.h"
#import "TXLocationSCViewController.h"
#import <TencentLBS/TencentLBS.h>
#import <CoreLocation/CoreLocation.h>
@interface ZJSILocationView ()<UITextFieldDelegate,TXLocationSCViewControllerDelegate>
/** 我的位置 */
@property (nonatomic, strong) UIButton *loactionButton;
/**  locaton  */
@property (strong, nonatomic)  TencentLBSLocation *tentLocation;

@end

@implementation ZJSILocationView

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title
{
    self = [super initWithFrame:frame title:title];
    if (self) {
        [self addSubview:self.loactionLabel];
        [self addSubview:self.loactionButton];
        [self getLocation];
    }
    return self;
}


- (void)getLocation{
        __weak typeof(self) weakSelf = self;
        [[ZJLocation sharedLocation] getLocationSuccess:^(NSDictionary *dict) {
            NSString *status = [NSString isNilStringReturnString:dict[@"State"]];
            NSString *city = [NSString isNilStringReturnString:dict[@"City"]];
            NSString *SubLocality = [NSString isNilStringReturnString:dict[@"SubLocality"]];
            NSString *Street = [NSString isNilStringReturnString:dict[@"Street"]];
            weakSelf.loactionLabel.text = [NSString stringWithFormat:@"%@%@%@%@",status,city,SubLocality,Street];
            NSDictionary *location = dict[@"location"];
            if (weakSelf.delegate) {
                [weakSelf.delegate ZJSILocationViewDelegate_latitude:location[@"latitude"] longitude:location[@"longitude"]];
            }
        }];

}

#pragma mark - 点击事件
- (void)action_loactionButtonClick:(UIButton *)button{

    TXLocationSCViewController *vc = [TXLocationSCViewController new];
    vc.delegate = self;
    [[self topViewController].navigationController pushViewController:vc animated:YES];
    
    
}

#pragma mark - TXLocationSCViewControllerDelegate
-(void)didSelectLocationPointWithLocationDictionary:(NSDictionary *)locationDictionary{
    NSDictionary *location = [locationDictionary objectForKey:@"latlng"];
    NSString *address = [locationDictionary objectForKey:@"poiaddress"];
    if (address.length == 0) {
        CLLocationDegrees latitude = [[location objectForKey:@"lat"] doubleValue];
        CLLocationDegrees longitude = [[location objectForKey:@"lng"] doubleValue];
        CLLocation *clllocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
        self.tentLocation.location = clllocation;
        [self reverseTenGeocoder:self.tentLocation];
        
    }else{
         self.loactionLabel.text = address;
    }
   
    
    if (self.delegate) {
        [self.delegate ZJSILocationViewDelegate_latitude:[location objectForKey:@"lat"] longitude:[location objectForKey:@"lng"]];
    }

}


/**  反地理解析  */

- (void)reverseTenGeocoder:(TencentLBSLocation *)Location{
    __weak typeof(self) weakSelf = self;
    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:Location.location completionHandler:^(NSArray *placemarks, NSError *error) {
        if(error || placemarks.count == 0){
            NSLog(@"error = %@",error);
        }else{
            CLPlacemark* placemark = placemarks.firstObject;
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict = [[placemark addressDictionary] mutableCopy];
            
            NSString *status = [NSString isNilStringReturnString:dict[@"State"]];
            NSString *city = [NSString isNilStringReturnString:dict[@"City"]];
            NSString *SubLocality = [NSString isNilStringReturnString:dict[@"SubLocality"]];
            NSString *Street = [NSString isNilStringReturnString:dict[@"Street"]];
            weakSelf.loactionLabel.text = [NSString stringWithFormat:@"%@%@%@%@",status,city,SubLocality,Street];
        }
    }];
    
}

#pragma mark - Setter
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (toBeString.length >= self.maxNumber && range.length!= 1 && self.maxNumber > 0){
        textField.text = [toBeString substringToIndex:self.maxNumber];
        return NO;
        
    }
    return YES;
}


#pragma mark - Getters
- (UITextField *)loactionLabel{
    if (_loactionLabel == nil){
        _loactionLabel = [[UITextField alloc] initWithFrame:CGRectMake(self.titleLabel.x, self.titleLabel.bottom, 295 * [UIScreen zj_screenWScale], 44 * [UIScreen zj_screenHScale])];
        _loactionLabel.text = @"";
        _loactionLabel.textColor = [UIColor textBlackColor];
        _loactionLabel.font = [UIFont titleTextFont];
        _loactionLabel.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        _loactionLabel.layer.borderWidth = 1;
        _loactionLabel.returnKeyType = UIKeyboardTypeTwitter;
        _loactionLabel.delegate = self;
        _loactionLabel.layer.borderColor = [UIColor zj_colorWithHexString:@"ebebeb"].CGColor;
        [_loactionLabel setTextFieldLeftforWidth:10 * [UIScreen zj_screenWScale]];
        [_loactionLabel setTextFieldRightforWidth:10 * [UIScreen zj_screenWScale]];
    }
    return _loactionLabel;
}

- (UIButton *)loactionButton{
    if (_loactionButton == nil){
        _loactionButton = [[UIButton alloc]initWithFrame: CGRectMake(self.width - self.loactionLabel.height - 12 * [UIScreen zj_screenWScale] , self.loactionLabel.y, self.loactionLabel.height, self.loactionLabel.height)];
        [_loactionButton setTitle:@"我的位置" forState:UIControlStateNormal];
        [_loactionButton setTitleColor:[UIColor zj_colorWithHexString:@"a8a8a8"] forState:UIControlStateNormal];
        _loactionButton.titleLabel.font = [UIFont systemFontOfSize:10 * [UIScreen zj_textFontScale]];
        [_loactionButton setImage:[UIImage imageNamed:@"mine_address"] forState:UIControlStateNormal];
        [_loactionButton addTarget:self action:@selector(action_loactionButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _loactionButton.titleEdgeInsets = UIEdgeInsetsMake(22 * [UIScreen zj_screenHScale], - _loactionButton.imageView.size.width, 0.0, 0.0);
        _loactionButton.imageEdgeInsets = UIEdgeInsetsMake(- 13 * [UIScreen zj_screenHScale], (_loactionButton.bounds.size.width - _loactionButton.imageView.size.width)/2, 0.0,(_loactionButton.bounds.size.width - _loactionButton.imageView.size.width)/2);
        
        _loactionButton.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        _loactionButton.layer.borderWidth = 1;
        _loactionButton.layer.borderColor = [UIColor zj_colorWithHexString:@"ebebeb"].CGColor;
    }
    return _loactionButton;
}

- (void)setImageString:(NSString *)imageString{
    _imageString = imageString;
    [self.loactionButton setBackgroundImage:[UIImage imageNamed:imageString] forState:UIControlStateNormal];
    [self.loactionButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.loactionButton setTitle:@"" forState:UIControlStateNormal];
     _loactionButton.layer.borderColor = [UIColor clearColor].CGColor;
}

- (TencentLBSLocation *)tentLocation{
    if (_tentLocation == nil) {
        _tentLocation = [TencentLBSLocation new];
    }
    return _tentLocation;
}

@end
